import createId from '@/lib/idCreator';
import Vue from 'vue'
import Vuex from 'vuex'
import clone from '../lib/clone';
import router from '../router/index';
import dayjs from 'dayjs';


Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    recordList: [] as RecordItem[],
    tagList: [] as Tag[],
    currentTag: undefined
  } as RootState,
  mutations: {
    setCurrentTag(state, id: string) {
      state.currentTag = state.tagList.filter(t => t.id === id)[0];
    },
    fetchRecords(state){
      state.recordList = JSON.parse(window.localStorage.getItem('recordList') || '[]') as RecordItem[]
    },
    createRecords(state,record: RecordItem){
      const record2 = clone(record);
      const formatDate = dayjs(record2.createdAt).format('YYYY-MM-DD');
      record2.createdAt = formatDate || new Date().toISOString();
      state.recordList.push(record2)
      store.commit('saveRecords')
    },
    saveRecords(state){
      window.localStorage.setItem('recordList',JSON.stringify(state.recordList))
    },
    // tagList
    fetchTags(state){
      state.tagList = JSON.parse(window.localStorage.getItem('tagList') || '[]') 
      if(!state.tagList || state.tagList.length === 0){
        store.commit('createTag' , '衣')
        store.commit('createTag' , '食')
        store.commit('createTag' , '住')
        store.commit('createTag' , '行')
      }
    },
    createTag(state,name:string){
      const names = state.tagList.map( item => item.name)
      if(names.indexOf(name) >= 0 ) { throw new Error("请不要创建重复的标签")} // new Error 返回的是false？
      const id = createId().toString()
      state.tagList.push({id,name})
      store.commit('saveTags')
    },
    updateTag(state,payload:{id:string,name:string}){
      const idList = state.tagList.map(item => item.id)
      if(idList.indexOf(payload.id) >= 0) {
          const names = state.tagList.map(item => item.name)
          if(names.indexOf(payload.name) >= 0){
              alert("请勿重复创建")
          }else {
              const tag = state.tagList.filter(item => item.id === payload.id)[0]
              tag.name = payload.name
              store.commit('saveTags')
          }
      }else {
          alert("没找到")
      }
    },
    removeTag(state,id:string){
      const removeItem = state.tagList.find(item => item.id === id)
      const removeIndex = state.tagList.indexOf(removeItem!)
      
      if(removeIndex >= 0){
          state.tagList.splice(removeIndex,1)
      }
      store.commit('saveTags')
      router.back()
    },
    saveTags(state){
      window.localStorage.setItem('tagList',JSON.stringify(state.tagList))
    }
  },
})

export default store
